import _ from 'lodash';
import * as api from '@/services/SupplyPlanMgr';
import * as utils from '../../utils/treeUtils';

const Model = {
  namespace: 'SupplyPlanDetailItems',
  state: {
    all: [],
    searched: [],
    expandedRowKeys: [],
    searchItems: {},
  },
  effects: {
    *init({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'save',
        payload: !payload.params.code
          ? {
              all: [],
              searched: [],
              expandedRowKeys: [],
              searchItems: {},
            }
          : {
              all: [],
              searched: [],
              expandedRowKeys: [],
            },
      });
      let year = yield select(state => state.SupplyPlanDetailItemsYears.currentYear);
      year = year || '';
      const params = { ...payload.params, year };
      const response = yield call(api.overAllValueUsingGET, { params });
      if (response && response.data && !_.isEmpty(response.data)) {
        const all = response.data;
        const searchItems = utils.getSearchItems(all);
        // 获取展开的列key  筛选过滤 type !== org_build
        const expandedRowKeys = utils.getExpandedRowKeys(
          _.filter(all, data => data.type !== 'org_build'),
        );
        const searched = utils.buildTree(all);
        yield put({
          type: 'save',
          payload: !payload.params.code
            ? { all, searched, expandedRowKeys, searchItems }
            : { all, searched, expandedRowKeys },
        });
      }
      if (callback) callback(response && response.data ? response.data : []);
    },
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    clear() {
      return {
        all: [],
        searched: [],
        expandedRowKeys: [],
        searchItems: {},
      };
    },
  },
};
export default Model;
